package pt.mleiria.crypto;

import pt.mleiria.messages.MessageVO;

public class Nshift implements CipherAlgorithms {

	private MessageVO msg;
	private int key;
	
	
	public void setKey(String key) {
		this.key = Integer.parseInt(key);
		if(this.key > CryptoUtils.alfabetLength){
			throw new IllegalArgumentException("0 < key <= " + CryptoUtils.alfabetLength);
		}
	}

	public void encryptText() {
		final char[] plainTextArr = msg.getMessage().toUpperCase().toCharArray();
		StringBuffer cipherText = new StringBuffer();
		for(char letter: plainTextArr){
			final int position = CryptoUtils.alfabetMap.get(letter);
			if(position + key >= CryptoUtils.alfabetLength){
				cipherText.append(CryptoUtils.getLetter((position + key) - CryptoUtils.alfabetLength));
			}else{
				cipherText.append(CryptoUtils.getLetter(position + key));
			}
		}
		msg.setMessageDigest(cipherText.toString());
	}

	public void decryptText() {
		final char[] cipherTextArr = msg.getMessageDigest().toUpperCase().toCharArray();
		StringBuffer plainText = new StringBuffer();
		for(char letter: cipherTextArr){
			final int position = CryptoUtils.alfabetMap.get(letter);
			if(position - key < 0){
				plainText.append(CryptoUtils.getLetter((position - key) + CryptoUtils.alfabetLength));
			}else{
				plainText.append(CryptoUtils.getLetter(position - key));
			}
		}
		msg.setMessage(plainText.toString());
	}
	public void setMessageVO(MessageVO msg) {
		this.msg = msg;
	}
	public MessageVO getMessageVO(){
		return this.msg;
	}

	
}
